import { PROCESS_TYPES } from '@/constants/ttsa'
import { useConfigStore } from '@/store/config'
import { useTtsaStore } from '@/store/ttsa'

export default function useLoading(emit?) {
  const config = useConfigStore()
  const ttsa = useTtsaStore()

  const process = computed(() => ttsa.process)
  const swiper = computed(() => config.swiper)

  const percentage = ref(0)

  const reset = () => {
    ttsa.init()
    loadingLoop()
  }

  // functions
  let timer
  const loadingLoop = () => {
    const totalTime = 1000 * 6, miniTime = 1000 * 1
    percentage.value = 0
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    let t = 0
    timer = setInterval(() => {
      percentage.value += 1
      t += 20
      if (t >= totalTime) {
        ttsa.process = PROCESS_TYPES.error
        return
      }
      if ((ttsa.process !== PROCESS_TYPES.opened || !ttsa.ttsa?.widgetSocket?.connected) && percentage.value > 98) {
        percentage.value = 98
        return
      }
      if (ttsa.process === PROCESS_TYPES.opened && ttsa.ttsa?.widgetSocket?.connected && t >= miniTime) {
        percentage.value = 100
        ttsa.process = PROCESS_TYPES.beforeStart
        emit && typeof emit === 'function' && emit('beforeStart')
        clearInterval(timer)
        timer = null
      } else if (percentage.value > 98) {
        percentage.value = 98
      }
    }, 20)
  }

  setTimeout(loadingLoop, 600)

  onBeforeUnmount(() => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  })

  return { process, swiper, percentage, reset }
}